package com.woniuxy.tfss.websocket;

import com.woniuxy.tfss.entity.Information;
import com.woniuxy.tfss.entity.Message;
import com.woniuxy.tfss.entity.Order;
import com.woniuxy.tfss.service.InformationService;
import com.woniuxy.tfss.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint(value = "/webSocket/{sid}", encoders = {ServerEncoder.class})
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    @Autowired
    private InformationService informationService;

    //发送消息
    public void sendMessage(Session session, Message<?> message) throws IOException, EncodeException {
        if (session != null) {
            synchronized (session) {
//                System.out.println("发送数据：" + message);
                session.getBasicRemote().sendObject(message);
            }
        }
    }

    //给指定用户或骑手发送信息
    public void sendInfo(String userName, Message<Order> message) {
        Session session = sessionPools.get(userName);
        try {
            sendMessage(session, message);
            Integer code = message.getCode();
            Information info = new Information();
            Order order=message.getData();
            if (code == 901) {
                info.setRecId(order.getRiderId());
                info.setRecType(Information.TORIDER);
                info.setContent("有系统派送的"+order.getNo()+"新订单,请尽快派送！订单详情请进入个人中心查看。");
            } else if (code == 902) {
                info.setRecId(Integer.parseInt(userName.substring(1,userName.length())));
                info.setRecType(Information.TORIDER);
                info.setContent("有新的预约单"+order.getNo()+"可以抢！快去个人中心看看吧。");
            } else if (code == 903) {
                info.setRecId(order.getUserId());
                info.setRecType(Information.TOUSER);
                info.setContent("您的"+order.getNo()+"预约订单已被抢,闪送员马上就来！");
            } else if (code == 904) {
                info.setRecId(order.getUserId());
                info.setRecType(Information.TOUSER);
                info.setContent("您的"+order.getNo()+"因无人抢单已被取消,请选择即时下单或者换个时间,带来的不便敬请谅解。");
            } else if (code == 905) {
                info.setRecId(order.getUserId());
                info.setRecType(Information.TOUSER);
                info.setContent("您的"+order.getNo()+"订单超过15分钟未支付,已被取消。");
            } else if (code == 906) {
                info.setRecId(order.getUserId());
                info.setRecType(Information.TOUSER);
                info.setContent("您的"+order.getNo()+"订单配送超时,请多一些宽容。系统已补偿一张八折券进入您的账户,详情请进入个人中心查看。");
            } else if (code == 907) {
                info.setRecId(order.getRiderId());
                info.setRecType(Information.TORIDER);
                info.setContent("您配送的"+order.getNo()+"订单超时了,搞快点！");
            } else if (code == 908) {
                info.setRecId(order.getRiderId());
                info.setRecType(Information.TORIDER);
                info.setContent("您配送的"+order.getNo()+"订单用户已经收货,辛苦了。");
            } else if (code == 909) {
                info.setRecId(order.getRiderId());
                info.setRecType(Information.TORIDER);
                info.setContent("您配送的"+order.getNo()+"订单用户申请赔偿,这可能会影响用户的评价以及您的信用分。以后请注意货物安全。");
            }
            info.setCode(code);
            info.setSeen(Information.NOTREAD);
            info.setRecTime(MyUtils.getNow());
            informationService.save(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName) {
        sessionPools.put(userName, session);
        addOnlineCount();
        System.out.println(userName + "加入webSocket！当前人数为" + onlineNum);
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
        System.out.println(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException {
//        message = "客户端：" + message + ",已收到";
//        System.out.println(message);
//        for (Session session: sessionPools.values()) {
//            try {
//                sendMessage(session, message);
//            } catch(Exception e){
//                e.printStackTrace();
//                continue;
//            }
//        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
